


class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return head;
        }

        while (head != null && head.val == val) {
            head = head.next;
        }

        ListNode prev = null;
        ListNode cur = head;

        while (cur != null) {
            prev = cur;
            cur = cur.next;

            while (cur != null && cur.val == val) {
                cur = cur.next;
            }
            prev.next = cur;
        }

        return head;
    }
}